<?php
/**
 * 用户管理API
 * User: zhangyale
 * Date: 2023/10/20
 */

namespace App\OpenApi\AdminApi\User;

use App\Library\Service\ExportService;
use App\Service\Core\Company\CompanyService;
use App\Service\Core\Service\Import\ImportService;
use App\Service\Core\User\User\UserListService;
use App\Service\Core\User\User\UserService;
use App\Service\Core\User\User\UserStoreService;
use App\Service\OpenApi\AdminApi\OpenBaseApi;
use App\Service\ParamsService;
use Box\Spout\Common\Type;
use Box\Spout\Reader\Common\Creator\ReaderFactory;

class UserApi extends OpenBaseApi
{
    /**
     * 用户列表
     * @return array
     */
    public function index(): array
    {
        $list_res = (new UserListService())
            ->setFields(['*', 'company_name', 'sex_name'])
            ->setMobile($this->input('mobile'))
            ->setUsername($this->input('username'))
            ->setStatus($this->input('status'))
            ->setCompanyId($this->input('company_id'))
            ->setUserIds($this->input('user_ids'))
            ->setPage($this->input('page', 1), $this->input('pageSize', $this->page_size))
            ->getList();
        return alert_info(0, 'ok', $list_res);
    }

    /**
     * 保存用户
     * @return array
     */
    public function store(): array
    {
        return (new UserStoreService())
            ->setOperate($this->operate_id, $this->operate_by)
            ->setUsername($this->input('username'))
            ->setMobile($this->input('mobile'))
            ->setCompanyId($this->input('company_id'))
            ->setSex($this->input('sex'))
            ->setBirthday($this->input('birthday'))
            ->setStatus($this->input('status'))
            ->setRemark($this->input('remark'))
//            ->setCanaddPatientUserNum($this->input('canadd_patient_user_num'))
            ->store($this->input('user_id'));
    }

    /**
     * 导入用户
     * @return array
     */
    public function import()
    {
        set_time_limit(0);
        ini_set('memory_limit', -1);
        $company_id = $this->input('company_id');
        if (!is_numeric($company_id) || $company_id <= 0) {
            return alert_info(1, '请选择单位');
        }
        $check_company = CompanyService::getInstance()->checkUserUsable($company_id);
        if ($check_company['code'] != 0) {
            return $check_company;
        }
        $file = request()->file('file');
        $ImportService = new ImportService();
        $check_res = $ImportService->checkImport($file);
        if ($check_res['code'] !== 0) {
            return alert_info(1, $check_res['msg']);
        }
        //导入数据
        $reader = ReaderFactory::createFromType(Type::XLSX);
        $reader->open($check_res['real_path']);
        $success_data = $failed_data = [];
        $error_num = $success_num = $row_num = 0;
        $result_rows = [];
        $error_key = 0;
        foreach ($reader->getSheetIterator() as $sheet) {
            foreach ($sheet->getRowIterator() as $row) {
                if ($row_num++ == 0) {
                    $data = $row->toArray();
                    if ($data[0] != '*姓名') {
                        return alert_info(1, '模板错误');
                    }
                    $error_key = count($data);
                    $result_rows[] = easy_xlsx_error($data, $error_key, '内容');
                    continue;
                }
                $data = $row->toArray();
                if (easy_is_empty_row($data)) {
                    continue;
                }
                if (is_object($data[3]) && !empty($data[3])) {
                    $data[3] = date('Y-m-d', strtotime(obj_to_array($data[3])['date']));//填时间对象会报错
                }
                $import_data = [
                    'username' => $data[0],
                    'sex' => $data[1],
                    'mobile' => $data[2],
                    'birthday' => $data[3],
                ];
                $import_res = (new UserStoreService())
                    ->setOperate($this->operate_id, $this->operate_by)
                    ->setUsername($import_data['username'])
                    ->setMobile($import_data['mobile'])
                    ->setCompanyId($company_id)
                    ->setSex($import_data['sex'])
                    ->setBirthday($import_data['birthday'])
                    ->setStatus(ParamsService::STATUS_ENABLE)
//                    ->setCanaddPatientUserNum(1)
                    ->setRemark('导入用户')
                    ->store(0);
                $import_data['company_name'] = $check_company['data']['company_name'];
                $import_data['error'] = $import_res['msg'];
                if ($import_res['code'] != 0) {
                    $error_num++;
                    $failed_data[] = $import_data;
                    $result_rows[] = easy_xlsx_error($data, $error_key, $import_res['msg']);
                } else {
                    $success_num++;
                    $import_data['user_id'] = $import_res['data']['user_id'];
                    $success_data[] = $import_data;
                }
            }
        }
        $data = ['success_num' => $success_num, 'success_data' => $success_data, 'error_num' => $error_num, 'failed_data' => $failed_data];
        if ($error_num > 0) {
            $file_path = $ImportService->createTempExcel($result_rows);
            $file_path = public_path(DIRECTORY_SEPARATOR . 'attached' . DIRECTORY_SEPARATOR . $file_path);
            $data['download_url'] = easy_url('download', ['file' => ExportService::encryptFilePath($file_path)]);
        }
        return alert_info(0, '导入结束，成功' . $success_num . '条，失败' . $error_num . '条', $data);
    }

    /**
     * 用户信息
     * @return array
     */
    public function info(): array
    {
        $info = UserService::getInstance()->getOne($this->input('user_id', $this->operate_id));
        return alert_info(0, 'ok', $info);
    }

    /**
     * 用户状态更改
     * @return array
     */
    public function changeStatus(): array
    {
        return UserService::getInstance()->changeStatus($this->input('user_id'), $this->input('status'), $this->operate_id, $this->operate_by);
    }

    /**
     * 删除用户
     * @return array
     */
    public function deleteUser(): array
    {
        return UserService::getInstance()->deleteUser($this->input('user_id'), $this->operate_id, $this->operate_by);
    }
}
